<template>
	<view class="content1">
		<!-- 头像选择区域 -->
		<image class="logo" :src="iconFilePath" @click="chooseImage()" mode="aspectFill"></image>
		<view class="tip" @click="chooseImage()">点击更换头像</view>
		
		<!-- 天气查询区域 -->
		<view class="weather-container">
			<button @click="getRequestWeather()" class="weather-btn">获取天气预报</button>
			<!-- 天气信息展示（默认隐藏） -->
			<view class="weather-info" v-if="weatherInfo">
				<view class="city">城市：{{ cityName }}</view>
				<view class="date">日期：{{ weatherInfo.date }}</view>
				<view class="type">天气：{{ weatherInfo.type }}</view>
				<view class="temp">温度：{{ weatherInfo.low }} ~ {{ weatherInfo.high }}</view>
				<view class="wind">风向：{{ weatherInfo.fx }}</view>
				<view class="notice">温馨提示：{{ weatherInfo.notice }}</view>
			</view>
		</view>
		<!-- 网络图片下载 -->
		<view class="weather-container">
					<!-- 下载按钮：下载中时禁用 -->
					<button 
						@click="dowmLoadFile()" 
						class="weather-btn"
						:disabled="isDownloading"
						
					>
						{{ isDownloading ? '下载中...' : '网络图片下载' }}
					</button>
					
					<!-- 下载进度条（下载中显示） -->
					<view class="progress-container" v-if="isDownloading">
						<view class="progress-tip">下载进度：{{ downloadProgress }}%</view>
						<view class="progress-bar">
							<view 
								class="progress-fill" 
								:style="{width: downloadProgress + '%'}"
							></view>
						</view>
						<view class="progress-detail">
							已下载：{{ formatFileSize(downloadedSize) }} / 
							总大小：{{ formatFileSize(totalSize) || '计算中' }}
						</view>
					</view>
					
					<!-- 下载结果提示（成功/失败后显示，3秒后自动隐藏） -->
					<view 
						class="download-result" 
						v-if="downloadResult"
						:class="{success: downloadResult === 'success', fail: downloadResult === 'fail'}"
					>
						{{ downloadResult === 'success' ? '下载成功！' : '下载失败！' }}
					</view>
				</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				iconFilePath: "/static/logo.png", // 默认头像
				weatherInfo: null, // 天气信息
				cityName: "厦门市" // 对应城市编码101230501
			};
		},
		onLoad() {
			// 页面加载时可自动获取一次天气
			// this.getRequestWeather();
		},
		methods: {
			// 选择图片（头像更换）
			chooseImage() {
				console.log("选择图片");
				uni.chooseImage({
					count: 6, 
					sizeType: ['original', 'compressed'], 
					sourceType: ['album', 'camera'], 
					success: (res) => {
						console.log("图片选择成功：", res.tempFilePaths[0]);
						// 预览图片
						uni.previewImage({
							urls: res.tempFilePaths,
						});
						// 更新头像路径
						this.iconFilePath = res.tempFilePaths[0];
					},
					fail: (err) => {
						console.log("图片选择失败：", err);
						uni.showToast({
							title: '图片选择失败',
							icon: 'none',
						});
					}
				});
			},
			// 获取天气预报
			getRequestWeather() {
				console.log("开始获取天气预报");
				// 显示加载中提示
				uni.showLoading({
					title: '获取中...'
				});
				
				uni.request({
					url: 'http://t.weather.sojson.com/api/weather/city/101230501',
					method: 'GET',
					timeout: 10000,
					success: (res) => {
						console.log("接口请求成功：", res.data);
						// 关闭加载提示
						uni.hideLoading();
						if (res.statusCode === 200 && res.data.status === 200) {
							// 获取明天的天气（forecast[0]是今天，[1]是明天）
							const tomorrowWeather = res.data.data.forecast[1];
							if (tomorrowWeather) {
								this.weatherInfo = tomorrowWeather;
								// 更新城市名称（从接口返回数据中获取更准确）
								this.cityName = res.data.cityInfo.city;
							} else {
								uni.showToast({
									title: '暂无明日天气数据',
									icon: 'none',
									duration: 1500
								});
							}
						} else {
							uni.showToast({
								title: `获取失败：${res.data.message || '未知错误'}`,
								icon: 'none',
								duration: 2000
							});
						}
					},
					fail: (err) => {
						console.log("接口请求失败：", err);
						// 关闭加载提示
						uni.hideLoading();
						uni.showToast({
							title: '网络异常，请检查网络',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			dowmLoadFile(){
				console.log("dowmLoadFile--网络图片下载");
				const imagetask = uni.downloadFile({
					url:'http://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg',
					success: (res) => {
						console.log("dowmLoadFile--success"+JSON.stringify(res));
						if(res.statusCode === 200){
							console.log("下载成功");
							uni.previewImage({
								urls:[res.tempFilePath]
							});
							this.iconFilePath=res.tempFilePath;
						}
					},
					fail: (err) => {
						console.log("dowmLoadFile--fail--" + err);
					}
				});
				imagetask.onProgressUpdate((res)=>{
					console.log("下载进度:"+res.progress+"%");
					console.log("已下载:"+res.totalBytesWrite);
					console.log("总大小:"+res.totalBytesExpectedToWrite);
				});
			},
			dowmLoadFile() {
							console.log("dowmLoadFile--网络图片下载");
							
							// 重置下载状态
							this.isDownloading = true;
							this.downloadProgress = 0;
							this.downloadedSize = 0;
							this.totalSize = 0;
							this.downloadResult = '';
							
							const imagetask = uni.downloadFile({
								url: 'http://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg',
								success: (res) => {
									console.log("dowmLoadFile--success", res);
									if (res.statusCode === 200) {
										console.log("下载成功");
										// 预览图片
										uni.previewImage({
											urls: [res.tempFilePath]
										});
										// 更新头像
										this.iconFilePath = res.tempFilePath;
										// 设置下载成功状态
										this.downloadResult = 'success';
									} else {
										console.log("下载失败：状态码", res.statusCode);
										this.downloadResult = 'fail';
									}
								},
								fail: (err) => {
									console.log("dowmLoadFile--fail", err);
									this.downloadResult = 'fail';
									uni.showToast({
										title: '下载失败：' + (err.errMsg || '网络错误'),
										icon: 'none',
										duration: 2000
									});
								},
								complete: () => {
									// 下载完成（成功/失败）后，3秒后隐藏结果提示，重置下载状态
									this.isDownloading = false;
									setTimeout(() => {
										this.downloadResult = '';
									}, 3000);
								}
							});
							
							// 监听下载进度
							imagetask.onProgressUpdate((res) => {
								console.log("下载进度:" + res.progress + "%");
								console.log("已下载:" + res.totalBytesWrite);
								console.log("总大小:" + res.totalBytesExpectedToWrite);
								
								// 更新进度数据
								this.downloadProgress = res.progress;
								this.downloadedSize = res.totalBytesWrite;
								this.totalSize = res.totalBytesExpectedToWrite;
							});
						},
						
						// 格式化文件大小（字节转KB/MB）
						formatFileSize(bytes) {
							if (bytes <= 0) return '0 B';
							const k = 1024;
							const sizes = ['B', 'KB', 'MB', 'GB'];
							const i = Math.floor(Math.log(bytes) / Math.log(k));
							return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
						}
					}
	};
</script>

<style scoped>
	.content1 {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 100rpx;
		border-radius: 50%;
		border: 2rpx solid #eee;
		
	}

	.tip {
		font-size: 24rpx;
		color: #666;
		margin: 20rpx 0 80rpx;
	}

	.weather-container {
		width: 90%;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.weather-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		border-radius: 40rpx;
		margin-bottom: 40rpx;
	}

	.weather-info {
		width: 100%;
		background-color: #f5f5f5;
		border-radius: 20rpx;
		padding: 30rpx;
		box-sizing: border-box;
	}

	.weather-info view {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 15rpx;
	}

	.weather-info .city {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #222;
	}

	.weather-info .notice {
		color: #ff6600;
		font-size: 26rpx;
	}
</style>